<?php
/**
 * Created by PhpStorm.
 * User: peter
 * Date: 2018/7/3
 * Time: 下午7:02
 */

namespace app\mall\logic;


use app\model\Distribution;
use app\model\MemberIncome;
use extend\Functions;
use extend\STATUS_CODE;
use extend\WeChatTemplateMessage;
use think\facade\Log;

class Profit
{
    /**
     * @purpose 获取账户资金
     * @param int $uid
     * @return array
     */
    public static function account (int $uid): array
    {
        $member         =   new \app\model\Member();
        $distribution   =   new Distribution();

        $balance        =   $member
            ->where('uid', $uid)
            ->value('balance');
        // 获取不可提现的金额
        $not_money      =   $distribution
            ->where(['uid' => $uid, 'status' => 1])
            ->sum('quota');
        return Functions::result(
            STATUS_CODE::SUCCESS,
            [
                'balance'   => $balance,
                'not_money' => $not_money
            ]
        );
    }

    /**
     * @purpose 获取待转入的资金
     * @param int $uid
     * @param int $page
     * @param int $size
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public static function waitRecordItem (int $uid, int $page = 1, int $size = 50): array
    {
        $model          = new Distribution();
        $result         = $model
            ->alias('d')
            ->leftJoin('member m', 'd.from_uid=m.uid')
            ->leftJoin('order o', 'd.order_id=o.id')
            ->field('d.from_uid,d.status,d.quota,d.level,d.order_id,m.nickname,m.avatar,FROM_UNIXTIME(o.pay_time, \'%Y-%m-%d %H:%i:%s\') as pay_time,FROM_UNIXTIME(o.create_at + 604800, \'%Y-%m-%d %H:%i:%s\') as estimate_time')
            ->order('d.create_at desc')
            ->where(['d.uid' => $uid, 'd.status' => 1])
            ->page($page, $size)
            ->select();
        return Functions::result(
            STATUS_CODE::SUCCESS,
            $result
        );
    }

    /**
     * @purpose 商品购买分销结算
     * @param int $order_id
     * @param string $order_no
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @throws \Exception
     */
    public static function settlement (int $order_id, string $order_no): bool
    {
        $distribution           = new Distribution();
        $member                 = new \app\model\Member();
        $member_income          = new MemberIncome();
//        $order                  = new \app\model\Order();
        $distribution_info      = $distribution
            ->alias('d')
            ->leftJoin('member m', 'd.uid=m.uid')
            ->leftJoin('wechat w', 'd.uid=w.uid')
            ->where('d.order_id', $order_id)
            ->field('d.id,d.uid,d.from_uid,d.status,d.quota,d.level,d.order_id,m.nickname,w.openid')
            ->select();
        $member_data = [];
        $member_income_data = [];
        $message = [];
        foreach ($distribution_info as $val) {
            $member_data[] = [
                'uid'       => $val->uid,
                'balance'   => ['inc', $val->quota]
            ];
            $member_income_data[] = [
                'uid'           => $val->uid,
                'type'          => 1,
                'quota'         => $val->quota,
                'description'   => '来自于'.([1 => '一级', 2 => '二级'][$val->level]).'盟友('.$val->nickname.')',
                'from_uid'      => $val->from_uid,
                'order_id'      => $order_id
            ];
            $_message = [
                'openid' => $val->openid,
                'quota'  => sprintf('%.2f', ($val->quota / 100)),
                'level'  => ([1 => '一级', 2 => '二级'][$val->level]),
                'time'  => date('Y-m-d H:i:s'),
                'nickname'  => $val->nickname,
                'order_no' => $order_no
            ];
            array_push($message, $_message);
        }
        $distribution->startTrans();
        $distribution_result    = $distribution
            ->isUpdate(true)
            ->save([
                'transfer_at' => time(),
                'status'      => 2
            ], ['order_id' => $order_id]);
        $member_result      = $member
            ->saveAll($member_data);
        $member_income_result = $member_income
            ->saveAll($member_income_data, false);
        if ($distribution && $member_result && $member_income_result && $distribution_result) {
            $distribution->commit();
            foreach ($message as $val) {
                WeChatTemplateMessage::income($val);
            }
            return true;
        }
        $distribution->rollback();
        return false;
    }

    /**
     * @purpose 获取用户收入记录列表
     * @param int $uid
     * @param int $page
     * @param int $size
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function income (int $uid, int $page, int $size): array
    {
        $model          = new MemberIncome();
        $result         = $model
            ->alias('mi')
            ->join('member m', 'mi.from_uid=m.uid')
            ->where(['mi.uid' => $uid])
            ->field('mi.type,mi.quota,mi.description,FROM_UNIXTIME(mi.create_at, \'%Y-%m-%d %H:%i:%s\') as create_date,m.avatar')
            ->order('mi.create_at desc')
            ->page($page, $size)
            ->select();
        return Functions::result(
            STATUS_CODE::SUCCESS,
            $result
        );
    }
}